package dst.ass1.jpa.interceptor;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.hibernate.EmptyInterceptor;

/**
 * 1.4.d.
 * use the of Hibernate Interceptor interface to count the number of database select statements that Hibernate
 * actually uses in the background
 * The Hibernate Interceptor interface provides callbacks from the session to the application, allowing the application to 
 * inspect and/or manipulate properties for a specific event
 *
 * !!!Should also be thread-safe!!!
 */
public class SQLInterceptor extends EmptyInterceptor {

	private static final long serialVersionUID = 3894614218727237142L;

	private static final AtomicInteger counter = new AtomicInteger(0);  //ThreadSafe because of Atomic Integer - operations of it are ThreadSafe

	private final static Logger LOGGER = Logger.getLogger(SQLInterceptor.class.getName());
	
    @Override
    public String onPrepareStatement(String sql) {
        if (Pattern.matches("select [ a-zA-Z0-9._,]+ from .*(TaskForce|Expert).*", sql)) {   //executed sql statement have to match the pattern
            counter.incrementAndGet();  //increment
            LOGGER.info("select on TaskForce or Expert");
        }

        return sql;
    }

    public static void resetCounter() {
    	counter.set(0);  //resetting Counter
    }


    public static int getSelectCount() {
    	return counter.get();   //get AtomicInteger value
    }
}
